﻿#include "B7CutMainWindow.h"
#include <QApplication>
#include <QFileDialog>

const int LeftRobot = 0;
const int RightRobot = 1;
B7CutMainWindow::B7CutMainWindow(QWidget *parent)
    :MainWindow(parent)
{

    QString path = qApp->applicationDirPath();
    QSettings settings( path + "/settings.ini", QSettings::IniFormat, this );
    m_scale[LeftRobot] = settings.value("Camera/LeftScale", 203).toDouble();
    m_scale[RightRobot] = settings.value("Camera/RightScale", 203).toDouble();
    m_logImagePath[LeftRobot] = settings.value("Path/LeftLogImage", "D:/Data/PicSave/").toString();
    m_logImagePath[RightRobot] = settings.value("Path/RightLogImage", "D:/Data/PicSave/").toString();
    m_recipePath[LeftRobot] = settings.value("Path/LeftRecipe", "D:/Data/LeftRecipe/").toString();
    m_recipePath[RightRobot] = settings.value("Path/RightRecipe", "D:/Data/RightRecipe/").toString();

    m_matcher[LeftRobot].setRecipePath(m_recipePath[LeftRobot]);
    m_matcher[RightRobot].setRecipePath(m_recipePath[RightRobot]);

    sqlLogger.loadSettings(settings);
    initInfoDockWidget();
    initRobotComm(settings);

    QStringList list{"L_L","L_R","R_L","R_R"};
    m_pCentreWidget->setString(list);

    connect(m_pPlcComm, &PlcComm::plcDataUpload, this, &B7CutMainWindow::robotDataUpload);
}

void B7CutMainWindow::robotDataUpload(int robot)
{
    m_InfoDockWidget[robot]-> setText("Data Upload to PLC");
}


void B7CutMainWindow::onLoadRecipe()
{
    int robotNo;
    DockWidgetInfo *pSender = (DockWidgetInfo *)sender();
    if(pSender == m_InfoDockWidget[LeftRobot] )
    {
        robotNo = LeftRobot;
    }
    else if(pSender == m_InfoDockWidget[RightRobot])
    {
        robotNo = RightRobot;
    }
    else
    {
        return;
    }
    QString fileName = QFileDialog::getOpenFileName(this,
         QStringLiteral("Open Recipe"), m_recipePath[robotNo], QStringLiteral("Recipe Files (*.ini)"));
    if(fileName.isEmpty())
    {
        return;
    }
    QFileInfo fileinfo = QFileInfo(fileName);
    m_recipePath[robotNo] = fileinfo.absolutePath();
    m_recipeName[robotNo] = fileinfo.baseName();
    pSender->setRecipeName(m_recipeName[robotNo]);

    m_matcher[robotNo].setRecipePath(m_recipePath[robotNo]);
    bool ret = m_matcher[robotNo].loadRecipe(m_recipeName[robotNo]);
    if(ret)
    {
        qDebug() << "m_matcher.loadRecipe success";
        m_pCentreWidget->setRects(robotNo, m_matcher[robotNo].panelRects());
       // m_pCentreWidget->setRect(robotNo, m_matcher[robotNo].leftPanelRect(), m_matcher[robotNo].rightPanelRect());
    }
}

void B7CutMainWindow::onDetect()
{
    int robotNo;
    DockWidgetInfo *pSender = (DockWidgetInfo *)sender();
    if(pSender == m_InfoDockWidget[LeftRobot] )
    {
        robotNo = LeftRobot;
    }
    else if(pSender == m_InfoDockWidget[RightRobot])
    {
        robotNo = RightRobot;
    }
    else
    {
        return;
    }
    QImage image = m_pImage[robotNo]->getImage();
    m_InfoDockWidget[robotNo]->setPanelID("user", "user");
    m_matcher[robotNo].panelDetect(image, "user", "user");
    afterDetect(robotNo);
}

void B7CutMainWindow::picSave(int channel, QString name)
{
    QDateTime dt = QDateTime::currentDateTime();
    QString dirName = dt.toString("yyyyMMdd");
    QString path = m_logImagePath[channel] + "/" + dirName + "/";
    QDir dir(path);
    if(!dir.exists())
    {
        dir.mkpath(path);
    }
    QString fullName = path + name + ".jpg";
    m_pImage[channel]->saveImage(fullName);
}

void B7CutMainWindow::writeLog(int robotNo)
{
    QPair<QString, QString> pair = m_InfoDockWidget[robotNo]->panelID();
    //double value[4];
    //value[0] = m_matcher[robotNo].m_leftShift.x;
   // value[1] = m_matcher[robotNo].m_leftShift.y;
   // value[2] = m_matcher[robotNo].m_leftRotateTheta;
    //value[3] = m_matcher[robotNo].m_leftScore;
    //sqlLogger.log(robotNo, 0, pair.first, )
}

void B7CutMainWindow::initInfoDockWidget()
{
    m_InfoDockWidget[LeftRobot] = new DockWidgetInfo(this);
    m_InfoDockWidget[RightRobot] = new DockWidgetInfo(this);
    m_InfoDockWidget[LeftRobot]->setWindowTitle("Left Robot");
    m_InfoDockWidget[RightRobot]->setWindowTitle("Right Robot");
    addDockWidget(Qt::RightDockWidgetArea, m_InfoDockWidget[LeftRobot]);
    addDockWidget(Qt::RightDockWidgetArea, m_InfoDockWidget[RightRobot]);

    connect(m_InfoDockWidget[LeftRobot], &DockWidgetInfo::detectTriggered, this, &B7CutMainWindow::onDetect);
    connect(m_InfoDockWidget[LeftRobot], &DockWidgetInfo::loadRecipeTriggered, this, &B7CutMainWindow::onLoadRecipe);

    connect(m_InfoDockWidget[RightRobot], &DockWidgetInfo::detectTriggered, this, &B7CutMainWindow::onDetect);
    connect(m_InfoDockWidget[RightRobot], &DockWidgetInfo::loadRecipeTriggered, this, &B7CutMainWindow::onLoadRecipe);
}

void B7CutMainWindow::updateRecipeAndDetect(int RobotNo, QString recipe, QString leftid, QString rightid)
{
    if(!recipe.isEmpty()) // 没有传 Recipe 就不更新 Recipe
    {
        m_recipeName[RobotNo] = recipe;
    }
    if(m_recipeName[RobotNo] != m_matcher[RobotNo].m_recipeName)
    {

        m_matcher[RobotNo].loadRecipe(m_recipeName[RobotNo]);
        m_pCentreWidget->setRects(RobotNo, m_matcher[RobotNo].panelRects());
        //m_pCentreWidget->setRect(RobotNo, m_matcher[RobotNo].leftPanelRect(), m_matcher[RobotNo].rightPanelRect());
    }
    m_InfoDockWidget[RobotNo]->setRecipeName(recipe);
    m_InfoDockWidget[RobotNo]->setText("updateRecipeAndDetect");
    //m_WaitForDetect[RobotNo] = true;
    //QTimer::singleShot(1000, this, SLOT(updateRecipeAndDetect2()));
    QImage image = m_pImage[RobotNo]->getImage();
    m_pPlcComm->SetGrabImageSuccess(RobotNo);
    m_matcher[RobotNo].panelDetect(image,  leftid, rightid);// 如果时 QPanel 模式，数据存在 left
    if(m_matcher->isOnePanelMode())
    {
        leftid = rightid;
        rightid = QString("");
    }
    m_InfoDockWidget[RobotNo]->setPanelID(leftid, rightid);
    afterDetect(RobotNo);
    updateRobotData(RobotNo);
}

void B7CutMainWindow::afterDetect(int robotNo)
{
    int N = 0;
    double x[2] = {0, 0}, y[2] = {0, 0}, theta[2] = {0, 0}, score[2] = {0, 0};
    double scale = m_scale[robotNo];
    m_matcher[robotNo].getData(scale, x, y, theta, score, N);
    qDebug() << "scale= " << scale << ",x = " << x[0] << ",score = " << score[0];

    QString recipeName = m_matcher[robotNo].recipeName();
    m_InfoDockWidget[robotNo]->setRecipeName(recipeName);
    QPair<QString, QString> id = m_InfoDockWidget[robotNo]->panelID();
    qDebug() << "ID = " << id;
    if(m_matcher->isOnePanelMode())
    {
        m_InfoDockWidget[robotNo]->setLeftPanelInfo(x[0], y[0], theta[0], score[0]);
        sqlLogger.log(robotNo, 0, id.first, x[0], y[0], theta[0], score[0], recipeName); //用 leftid， 但是 x[0]数据
    }
    else
    {
        if(!id.first.isEmpty()) //左边的数据放在 x[1]
        {
            m_InfoDockWidget[robotNo]->setLeftPanelInfo(x[1], y[1], theta[1], score[1]);
            sqlLogger.log(robotNo, 0, id.first, x[1], y[1], theta[1], score[1], recipeName);
        }
        else
        {
            m_InfoDockWidget[robotNo]->setLeftPanelInfo(-1, -1, -1, 0);
        }
        if(!id.second.isEmpty()) // 右边的数据放在 x[0]
        {
            m_InfoDockWidget[robotNo]->setRightPanelInfo(x[0], y[0], theta[0], score[0]);
            sqlLogger.log(robotNo, 1, id.second, x[0], y[0], theta[0], score[0], recipeName);
        }
        else
        {
            m_InfoDockWidget[robotNo]->setRightPanelInfo(-1, -1, -1, 0);
        }
    }

    QString fileName;
    if(id.first.isEmpty())
    {
        QDateTime dt = QDateTime::currentDateTime();
        fileName = dt.toString("yyyyMMddhhmmss");
    }
    else if(id.second.isEmpty())
    {
        fileName = id.first;
    }
    else
    {
        fileName = id.first + "_" + id.second;
    }

    picSave(robotNo, fileName);
}

void B7CutMainWindow::updateRecipeAndDetect2()
{
    if(m_WaitForDetect[LeftRobot])
    {
        QImage image = m_pImage[LeftRobot]->getImage();
        QPair<QString, QString> pair = m_InfoDockWidget[LeftRobot]->panelID();
        m_matcher[LeftRobot].panelDetect(image, pair.second, pair.first);
        afterDetect(LeftRobot);
        updateRobotData(LeftRobot);
        m_WaitForDetect[LeftRobot] = false;
    }
    if(m_WaitForDetect[RightRobot])
    {
        QImage image = m_pImage[RightRobot]->getImage();
        QPair<QString, QString> pair = m_InfoDockWidget[RightRobot]->panelID();
        m_matcher[RightRobot].panelDetect(image, pair.second, pair.first);
        afterDetect(RightRobot);
        updateRobotData(RightRobot);
        m_WaitForDetect[RightRobot] = false;
    }
}

void B7CutMainWindow::initRobotComm(QSettings &settings)
{
    QString plcIp = settings.value("PLC/IP", "192.6.95.1").toString();
    int plcPort = settings.value("PLC/Port", 8000).toInt();

    m_pPlcComm = new PlcComm(this);
    connect(m_pPlcComm, &PlcComm::offsetDisable, this, &B7CutMainWindow::offsetDisable);
    connect(m_pPlcComm, &PlcComm::trigger, this, &B7CutMainWindow::updateRecipeAndDetect);// 开始拍照检测
    connect(m_pPlcComm, &PlcComm::plcConnected, m_InfoDockWidget[LeftRobot], &DockWidgetInfo::onRobotConnected);
    connect(m_pPlcComm, &PlcComm::plcConnected, m_InfoDockWidget[RightRobot], &DockWidgetInfo::onRobotConnected);
    connect(m_pPlcComm, &PlcComm::plcDisconnected, m_InfoDockWidget[LeftRobot], &DockWidgetInfo::onRobotDisconnected);
    connect(m_pPlcComm, &PlcComm::plcDisconnected, m_InfoDockWidget[RightRobot], &DockWidgetInfo::onRobotDisconnected);
    m_pPlcComm->connectToRobot(plcIp, plcPort);
}

void B7CutMainWindow::offsetDisable(int robotNo)
{
    m_InfoDockWidget[robotNo]->setRecipeName("");
    m_InfoDockWidget[robotNo]->setPanelID("", "");
    m_InfoDockWidget[robotNo]->setLeftPanelInfo(0,0, 0, 0);
    m_InfoDockWidget[robotNo]->setRightPanelInfo(0,0, 0, 0);
}

void B7CutMainWindow::updateRobotData(int robot)
{
    m_InfoDockWidget[robot]->setText(""); // 先清空
    int N = 0;
    double scale = m_scale[robot];
    double x[2] = {0, 0}, y[2] = {0, 0}, theta[2] = {0, 0}, score[2] = {0, 0};
    m_matcher[robot].getData(scale, x, y, theta, score, N);

    // x[0] 对应  rightid
    if ((m_matcher[robot].m_leftPanelLocateFailed && m_matcher[robot].m_hasLeftPanel)
            || (m_matcher[robot].m_rightPanelLocateFailed && m_matcher[robot].m_hasRightPanel))
    {
        m_pPlcComm->SetMatchModelFaild(robot);
        m_InfoDockWidget[robot]->setText("matchModelFail");
        return;
    }

    if(robot==RIGHT_ROBOT)
    {
        //std::swap(x[0],x[1]);
        //std::swap(y[0],y[1]);
        //std::swap(theta[0],theta[1]);

        x[0]=-x[0];
        x[1]=-x[1];
        y[0]=-y[0];
        y[1]=-y[1];
    }

    bool ret = m_pPlcComm->setData(robot, x, y, theta, N);
    if(ret)
    {
        m_InfoDockWidget[robot]->setText("updateRobotData");
    }
    return;
}
